<?php

namespace App\Http\Controllers\Admin\Wechat\Fun;

use Illuminate\Http\Request;
use App\Http\Controllers\AdminController;

use Validator;
use DB;
use Log;

class MenusController extends AdminController
{
    /**
     * 获取列表
     * @return [type] [description]
     */
    function getLists(Request $request){
        $menus = DB::table('wechat_menu')->select('id','pid','type','key','keyword_id','url','name','displayOrder')->orderBy('displayOrder','asc')->get();
        $datas = [];

        //格式化数据,并对数据进行排序
        foreach ($menus as $key => $menu) {
            if(!$menu->pid){
                $datas[] = $menu;
            }
        }
        foreach ($datas as $data) {
            foreach ($menus as $menu) {
                if($data->id == $menu->pid){
                    $data->sub_button[] = $menu;
                }
            }
            if(isset($data->sub_button)){
                $data->sub_button = array_sort($data->sub_button, function ($value) {
                    return $value->displayOrder;
                });
            }else{
                $data->sub_button = [];
            }
        }
        //解析数据
        foreach ($datas as $key => $data) {
            $data->current = false;
            switch ($data->type) {
                case 'click':
                    $data->menuType = 'message';
                    break;
                case 'view':
                    $data->menuType = 'link';
                    break;
            }
            $data->sub_show = false;
            $data->link = $data->url;
            unset($data->type,$data->url,$data->key,$data->displayOrder,$data->pid);
            foreach ($data->sub_button as $key => $child ) {
                $child->current = false;
                switch ($child->type) {
                    case 'click':
                        $child->menuType = 'message';
                        break;
                    case 'view':
                        $child->menuType = 'link';
                        break;
                }
                $child->link = $child->url;
                $child->sub_button = [];
                unset($child->type,$child->url,$child->key,$child->displayOrder,$child->pid);
            }
        }


        $this->ajaxJson(0,'',$datas);
    } 
	

    /**
     * 更新菜单
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function updateMenu(Request $request){
    	$requests = $request->all();
    	foreach ($requests as $data) {
	    	$validator = $this->formValidator($data);
	        if($validator->fails()){
	            $this->ajaxJson(1,$validator->errors()->first());
	        }
            if(!isset($data['sub_button'])){
                continue;
            }
            foreach ($data['sub_button'] as $child) {
                $validator = $this->formValidator($child);
                if($validator->fails()){
                    $this->ajaxJson(1,$validator->errors()->first());
                }
            }
    	}

        try {
            DB::beginTransaction();
            foreach ($requests as $key=> $request) {
                $pid = 0;
                $data = [];
                switch ($request['menuType']) {
                    case 'message':
                        if(!isset($request['sub_button'])){
                            $data['key']        = DB::table('wechat_keyword')->find($request['keyword_id'])->keyword;
                            $data['keyword_id'] = $request['keyword_id'];   
                        }
                        
                        $data['type'] = 'click';
                        break;
                    case 'link':
                        if(!isset($request['sub_button'])){
                            $data['url'] = $request['link'];
                        }
                        $data['type'] = 'view';
                        break;
                }
                $data['name']         = $request['name'];
                $data['updated_at']   = date('Y-m-d H:i:s');
                $data['displayOrder'] = $key;

                if($request['id']){
                    $pid = $request['id'];
                    DB::table('wechat_menu')->where('id',$request['id'])->update($data);
                }else{
                    $data['created_at'] = date('Y-m-d H:i:s');                    
                    $pid = DB::table('wechat_menu')->insertGetId($data);
                }

                if(!isset($request['sub_button'])){
                    continue;
                }
                $subButtons = $request['sub_button'];
                foreach ($subButtons as $subKey => $sub) {
                    $data = [];
                    $data['pid'] = $pid;
                    switch ($sub['menuType']) {
                        case 'message':
                            $data['key']        = DB::table('wechat_keyword')->find($sub['keyword_id'])->keyword;
                            $data['keyword_id'] = $sub['keyword_id'];
                            $data['type']       = 'click';
                            break;
                        case 'link':
                            $data['url']  = $sub['link'];
                            $data['type'] = 'view';
                            break;
                    }
                    $data['name']         = $sub['name'];
                    $data['updated_at']   = date('Y-m-d H:i:s');
                    $data['displayOrder'] = $subKey;

                    if($sub['id']){
                        DB::table('wechat_menu')->where('id',$sub['id'])->update($data);
                    }else{
                        $data['created_at'] = date('Y-m-d H:i:s');                    
                        DB::table('wechat_menu')->insert($data);
                    }
                }
            }
            DB::commit();
            $this->ajaxJson(0,'更新成功');
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->ajaxJson(1,'更新失败');
        }
    }

    /**
     * 删除菜单
     * @return [type] [description]
     */
    public function deleteMenu($menu_id){
        $menu = DB::table('wechat_menu')->find($menu_id);
        if(!$menu){
            $this->ajaxJson(1,'未知菜单数据');
        }
        try {
            DB::beginTransaction();
            DB::table('wechat_menu')->where('id',$menu_id)->delete();
            DB::table('wechat_menu')->where('pid',$menu_id)->delete();
            DB::commit();
            $this->ajaxJson(0,'更新成功');
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->ajaxJson(1,'更新失败');
        }
    }

    /**
     * 菜单发布到微信
     * @return [type] [description]
     */
    public function releaseMenu(Request $request){
        $menus = DB::table('wechat_menu')->select('id','pid','type','key','keyword_id','url','name','displayOrder')->orderBy('displayOrder','asc')->get();
        $buttons = [];

        //格式化数据,并对数据进行排序
        foreach ($menus as $key => $menu) {
            if(!$menu->pid){
                $data = [
                    'id' => $menu->id,
                    'type' => $menu->type,
                    'name' => $menu->name,
                    'url' => $menu->url,
                    'key' => $menu->key,
                ];
                $buttons[] = $data;
            }
        }
        foreach ($buttons as  $key => $button) {
            foreach ($menus as $menu) {
                if($button['id'] == $menu->pid){
                    $data = [
                        'type' => $menu->type,
                        'name' => $menu->name,
                        'url'  => $menu->url,
                        'key'  => $menu->key,
                        'displayOrder' => $menu->displayOrder,
                    ];
                    $buttons[$key]['sub_button'][] = $data;
                }
            }
            if(isset($button['sub_button'])){
                $button['sub_button'] = array_sort($button['sub_button'], function ($value) {
                    return $value['displayOrder'];
                });
            }
        }
        try {
            app('wechat.official_account')->menu->create($buttons);
            $this->ajaxJson(0,'发布成功');
        } catch (\Exception $e) {
            Log::error('【'.$e->getMessage().'】'.'【'.$e->getFile().'】'.'【'.$e->getTraceAsString ().'】');
            $this->ajaxJson(1,'发布失败');
        }
    }

    /**
     * 表单验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function formValidator(array $data){
        $attribute =  array(
            'id'         => '菜单数据',
            'name'       => '菜单名称',
            'menuType'   => '菜单内容',
            'keyword_id' => '关键词',
            'link'       => '页面地址',
           
        );

        $message  = array(
            'required'    => ':attribute必须填写',
            'in'          => ':attribute 必须是以下的类型之一： :values',
            'array'       => ':attribute 必须是数组',
            'numeric'     => ':attribute 必须是数值',
            'required_if' => ':attribute 缺少参数',
            'url'         => ':attribute不是一个合法的网页链接',
            'exists'      => ':attribute 在数据库中不存在,数据错误',
        );

        $v = Validator::make($data, [
            'name'                     => 'bail|required',
            'menuType'                 => 'bail|required|in:link,message',
        ],$message,$attribute);
        //当菜单类型是链接,验证链接格式
        $v->sometimes('link' , 'url',function($data){
            if($data['menuType']=='link'){
                return true;
            }
            return false;
        });
        //菜单类型是消息,验证关键词
        if(isset($data['sub_button'])==0){
            $v->sometimes('keyword_id' , 'numeric|exists:wechat_keyword,id',function($data){
                if($data['menuType']=='message'){
                    return true;
                }
                return false;
            });    
        }
        //验证菜单数据
        $v->sometimes('id' , 'numeric|exists:wechat_menu,id',function($data){
            if($data['id']>0){
                return true;
            }
            return false;
        });
        return $v;
    }
}
